package com.ruoyi.system.service.impl;

import com.alibaba.nacos.shaded.com.google.common.base.Joiner;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.constant.CommonConstant;
import com.ruoyi.system.constant.ExceptionConstant;
import com.ruoyi.system.domain.OrderInitiate;
import com.ruoyi.system.domain.OrderLink;
import com.ruoyi.system.domain.OrderLinkRealize;
import com.ruoyi.system.domain.vo.OperationTreeVo;
import com.ruoyi.system.mapper.OrderInitiateMapper;
import com.ruoyi.system.mapper.OrderLinkMapper;
import com.ruoyi.system.mapper.OrderLinkRealizeMapper;
import com.ruoyi.system.mapper.OrderOperationMapper;
import com.ruoyi.system.service.IOrderLinkService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.system.constant.CommonConstant.THREE;
import static com.ruoyi.system.constant.CommonConstant.ZERO;

/**
 * 订单环节管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-09
 */
@Service
public class OrderLinkServiceImpl implements IOrderLinkService 
{
    private static final Logger log = LoggerFactory.getLogger(OrderLinkServiceImpl.class);

    @Autowired
    private OrderLinkMapper orderLinkMapper;

    @Autowired
    private OrderInitiateMapper orderInitiateMapper;

    @Autowired
    private OrderLinkRealizeMapper orderLinkRealizeMapper;

    /**
     * 查询订单环节管理
     * 
     * @param id 订单环节管理主键
     * @return 订单环节管理
     */
    @Override
    public OrderLink selectOrderLinkById(Long id)
    {
        return orderLinkMapper.selectOrderLinkById(id);
    }

    /**
     * 查询员工环节权限
     *
     * @param nameOrOrderId 名称或订单id
     * @return 订单环节管理
     */
    @Override
    public List<OperationTreeVo> dropDown(String nameOrOrderId)
    {
        try {
            OrderLink orderLink = new OrderLink();
            orderLink.setAssignEmployees(SecurityUtils.getUsername());
            // 当前用户能够涉及的环节
            List<OrderLink> orderLinks = orderLinkMapper.selectOrderLinkList(orderLink);
            if (ObjectUtils.isEmpty(orderLinks)) {
                return Collections.EMPTY_LIST;
            }
            List<Long> linkIds = orderLinks.stream().map(OrderLink::getId).collect(Collectors.toList());
            List<OrderLinkRealize> orderLinkRealizes = orderLinkRealizeMapper.selectOrderLinkRealizeListByLinkIds(linkIds);
            if (ObjectUtils.isEmpty(orderLinkRealizes)) {
                return Collections.EMPTY_LIST;
            }
            List<Long> orderIds = orderLinkRealizes.stream().map(OrderLinkRealize::getOrderId).collect(Collectors.toList());
            // 员工能够选择的订单(只查询已下发状态)
            List<OperationTreeVo> initiateList = orderInitiateMapper.selectOrderInitiates(orderIds, nameOrOrderId);
            if (ObjectUtils.isEmpty(initiateList)) {
                return Collections.EMPTY_LIST;
            }
            // 订单map
            Map<Long, OperationTreeVo> initiateMap = initiateList
                    .stream()
                    .distinct()
                    .collect(Collectors.toMap(OperationTreeVo::getOrderId, s -> s, (key1, key2) -> key1));
            // 订单map
            Map<String, OperationTreeVo> initiateInfoMap = initiateList
                    .stream()
                    .distinct()
                    .collect(Collectors.toMap(vo -> String.valueOf(vo.getOrderId()) + vo.getLinkId(), s -> s, (key1, key2) -> key1));
            // 环节map-key：订单id + 环节id + 顺序id（用于查询上一步环节的合格总数量）
            Map<String, OrderLinkRealize> orderLinkRealizeMap = orderLinkRealizes
                    .stream()
                    .distinct()
                    .collect(Collectors.toMap(vo -> String.valueOf(vo.getOrderId()) + vo.getLinkOrder(), s -> s, (key1, key2) -> key1));
            return initialize(orderLinkRealizes, initiateMap, initiateInfoMap, orderLinkRealizeMap);
        } catch (Exception e) {
            log.error("FAIL updateOrderInitiate error is:{}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 查询订单环节全量信息-下拉
     *
     * @param orderLinkRealizes 订单环节列表信息
     * @param initiateMap 订单信息map
     * @param initiateInfoMap 订单信息map（用于判定录入数量）
     * @param orderLinkRealizeMap 订单环节列表信息map
     * @return List
     */
    public List<OperationTreeVo> initialize(List<OrderLinkRealize> orderLinkRealizes,
                                            Map<Long, OperationTreeVo> initiateMap,
                                            Map<String, OperationTreeVo> initiateInfoMap,
                                            Map<String, OrderLinkRealize> orderLinkRealizeMap) {
        List<OperationTreeVo> operationTreeVoList = new ArrayList<>();
        orderLinkRealizes.forEach(vo -> {
            // 用于判定环节是否存在
            OperationTreeVo operationTreeVo = initiateMap.get(vo.getOrderId());
            // 用于判断录入数量
            OperationTreeVo operationTreeInfoVo = initiateInfoMap.get(String.valueOf(vo.getOrderId()) + vo.getLinkId());
            if (ObjectUtils.isEmpty(operationTreeVo)) {
                return;
            }
            OperationTreeVo operationTree = new OperationTreeVo();
            operationTree.setOrderId(operationTreeVo.getOrderId());
            operationTree.setOrderName(operationTreeVo.getOrderName());
            // 如果环节为第一步，则总数量为订单总数量
            if (vo.getLinkOrder() == 0) {
                operationTree.setNumber(operationTreeVo.getNumber());
            } else {
                // 根据顺序，查询上一步的环节信息
                OrderLinkRealize orderLinkRealize = orderLinkRealizeMap.get(String.valueOf(vo.getOrderId()) + (vo.getLinkOrder() - 1));
                if (ObjectUtils.isNotEmpty(orderLinkRealize)) {
                    // 总数量：上一环节已经完成的数量
                    operationTree.setNumber(orderLinkRealize.getFinishNumber());
                }
            }
            if (ObjectUtils.isNotEmpty(operationTreeInfoVo)) {
                // 剩余数量：总数量 - 待审核数量 - 已审核通过的数量
                operationTree.setResidueNumber(operationTree.getNumber() -
                        (ObjectUtils.isEmpty(operationTreeVo.getInputNumber()) ? 0 : operationTreeVo.getInputNumber()));
            } else {
                // 该环节未录入数据时：上一步数量等于该环节剩余数量
                operationTree.setResidueNumber(operationTree.getNumber());
            }
            operationTree.setOrderLinkRealize(vo);
            // 审核数量不为空则显示到我的待办
            if (operationTree.getResidueNumber() != 0) {
                operationTreeVoList.add(operationTree);
            }
        });
        return operationTreeVoList;
    }

    /**
     * 查询订单环节全量信息-下拉
     *
     * @return 订单环节管理
     */
    @Override
    public List<OrderLink> selectAllList() {
        OrderLink orderLink = new OrderLink();
        List<OrderLink> orderLinks = orderLinkMapper.selectOrderLinkList(orderLink);
        if (ObjectUtils.isNotEmpty(orderLinks)) {
            orderLinks = orderLinks.stream().map(vo -> {
                OrderLink orderLinkInfo = new OrderLink();
                orderLinkInfo.setId(vo.getId());
                orderLinkInfo.setLinkName(vo.getLinkName());
                return orderLinkInfo;
            }).collect(Collectors.toList());
        }
        return orderLinks;
    }

    /**
     * 查询订单环节管理列表
     * 
     * @param orderLink 订单环节管理
     * @return 订单环节管理
     */
    @Override
    public List<OrderLink> selectOrderLinkList(OrderLink orderLink)
    {
        return orderLinkMapper.selectOrderLinkList(orderLink);
    }

    /**
     * 新增订单环节管理
     * 
     * @param orderLink 订单环节管理
     * @return 结果
     */
    @Override
    public int insertOrderLink(OrderLink orderLink)
    {
        orderLink.setCreateTime(DateUtils.getNowDate());
        orderLink.setUpdateTime(DateUtils.getNowDate());
        orderLink.setCreateBy(SecurityUtils.getUsername());
        orderLink.setUpdateBy(SecurityUtils.getUsername());
        orderLink.setDeleteFlag(CommonConstant.DELETE_FLAG_N);
        return orderLinkMapper.insertOrderLink(orderLink);
    }

    /**
     * 修改订单环节管理
     * 
     * @param orderLink 订单环节管理
     * @return 结果
     */
    @Override
    public int updateOrderLink(OrderLink orderLink)
    {
        orderLink.setUpdateBy(SecurityUtils.getUsername());
        orderLink.setUpdateTime(DateUtils.getNowDate());
        return orderLinkMapper.updateOrderLink(orderLink);
    }

    /**
     * 批量删除订单环节管理
     * 
     * @param ids 需要删除的订单环节管理主键
     * @return 结果
     */
    @Override
    public int deleteOrderLinkByIds(Long[] ids)
    {
        // 被引用的环节不可删除
        List<OrderLinkRealize> orderLinkRealizes = orderLinkRealizeMapper.selectOrderLinkRealizeListByLinkIds(Arrays.asList(ids));
        if (ObjectUtils.isNotEmpty(orderLinkRealizes)) {
            // 所有已使用的环节
            List<Long> linkIds = orderLinkRealizes
                    .stream()
                    .distinct()
                    .map(OrderLinkRealize::getLinkId)
                    .collect(Collectors.toList());
            // 环节名称集合
            List<String> linkNameList = orderLinkMapper.selectOrderLinkByIds(linkIds)
                    .stream()
                    .map(OrderLink::getLinkName)
                    .collect(Collectors.toList());
            throw new RuntimeException(Joiner.on(CommonConstant.COMMA).join(linkNameList) + ExceptionConstant.LINK_NOE_DELETE);
        }
        return orderLinkMapper.deleteOrderLinkByIds(ids);
    }
}
